
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>secrets --- 生成安全随机数字用于管理密码 &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="通用操作系统服务" href="allos.html" />
    <link rel="prev" title="hmac --- 基于密钥的消息验证" href="hmac.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/secrets.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="allos.html" title="通用操作系统服务"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="hmac.html" title="hmac --- 基于密钥的消息验证"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" accesskey="U">加密服务</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-secrets">
<span id="secrets-generate-secure-random-numbers-for-managing-secrets"></span><h1><a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code></a> --- 生成安全随机数字用于管理密码<a class="headerlink" href="#module-secrets" title="永久链接至标题">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified added">3.6 新版功能.</span></p>
</div>
<p><strong>源代码:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/secrets.py">Lib/secrets.py</a></p>
<hr class="docutils" />
<p><a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code></a> 模块可用于生成高加密强度的随机数，适应管理密码、账户验证、安全凭据和相关机密数据管理的需要。</p>
<p>特别地，应当优先使用 <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code></a> 来替代 <a class="reference internal" href="random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> 模块中默认的伪随机数生成器，后者被设计用于建模和仿真，而不适用于安全和加密。</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0506"><strong>PEP 506</strong></a></p>
</div>
<div class="section" id="random-numbers">
<h2>随机数<a class="headerlink" href="#random-numbers" title="永久链接至标题">¶</a></h2>
<p>通过 <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code></a> 模块可以访问你的操作系统所能提供的最安全的随机性来源。</p>
<dl class="class">
<dt id="secrets.SystemRandom">
<em class="property">class </em><code class="sig-prename descclassname">secrets.</code><code class="sig-name descname">SystemRandom</code><a class="headerlink" href="#secrets.SystemRandom" title="永久链接至目标">¶</a></dt>
<dd><p>使用操作系统所提供的最高质量源来生成随机数的类。 请参阅 <a class="reference internal" href="random.html#random.SystemRandom" title="random.SystemRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">random.SystemRandom</span></code></a> 了解更多细节。</p>
</dd></dl>

<dl class="function">
<dt id="secrets.choice">
<code class="sig-prename descclassname">secrets.</code><code class="sig-name descname">choice</code><span class="sig-paren">(</span><em class="sig-param">sequence</em><span class="sig-paren">)</span><a class="headerlink" href="#secrets.choice" title="永久链接至目标">¶</a></dt>
<dd><p>返回从一个非空序列中随机选取的元素。</p>
</dd></dl>

<dl class="function">
<dt id="secrets.randbelow">
<code class="sig-prename descclassname">secrets.</code><code class="sig-name descname">randbelow</code><span class="sig-paren">(</span><em class="sig-param">n</em><span class="sig-paren">)</span><a class="headerlink" href="#secrets.randbelow" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个 [0, <em>n</em>) 范围之内的随机整数。</p>
</dd></dl>

<dl class="function">
<dt id="secrets.randbits">
<code class="sig-prename descclassname">secrets.</code><code class="sig-name descname">randbits</code><span class="sig-paren">(</span><em class="sig-param">k</em><span class="sig-paren">)</span><a class="headerlink" href="#secrets.randbits" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个具有 <em>k</em> 个随机比特位的整数。</p>
</dd></dl>

</div>
<div class="section" id="generating-tokens">
<h2>生成凭据<a class="headerlink" href="#generating-tokens" title="永久链接至标题">¶</a></h2>
<p><a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code></a> 模块提供了一些生成安全凭据的函数，适用于诸如密码重置、难以猜测的 URL 之类的应用场景。</p>
<dl class="function">
<dt id="secrets.token_bytes">
<code class="sig-prename descclassname">secrets.</code><code class="sig-name descname">token_bytes</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">nbytes=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#secrets.token_bytes" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个包含 <em>nbytes</em> 个字节的随机字节串。 如果 <em>nbytes</em> 为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 或未提供，则会使用一个合理的默认值。</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">token_bytes</span><span class="p">(</span><span class="mi">16</span><span class="p">)</span>  
<span class="go">b&#39;\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="secrets.token_hex">
<code class="sig-prename descclassname">secrets.</code><code class="sig-name descname">token_hex</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">nbytes=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#secrets.token_hex" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个十六进制数码形式的随机字符串。 字符串具有 <em>nbytes</em> 个随机字节，每个字节转换为两个十六进制数码。 如果 <em>nbytes</em> 为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 或未提供，则会使用一个合理的默认值。</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">token_hex</span><span class="p">(</span><span class="mi">16</span><span class="p">)</span>  
<span class="go">&#39;f9bf78b9a18ce6d46a0cd2b0b86df9da&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="secrets.token_urlsafe">
<code class="sig-prename descclassname">secrets.</code><code class="sig-name descname">token_urlsafe</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">nbytes=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#secrets.token_urlsafe" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个 URL 安全的随机字符串，包含 <em>nbytes</em> 个随机字节。 文本将使用 Base64 编码，因此平均来说每个字节将对应 1.3 个结果字符。 如果 <em>nbytes</em> 为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 或未提供，则会使用一个合理的默认值。</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">token_urlsafe</span><span class="p">(</span><span class="mi">16</span><span class="p">)</span>  
<span class="go">&#39;Drmhze6EPcv0fN_81Bj-nA&#39;</span>
</pre></div>
</div>
</dd></dl>

<div class="section" id="how-many-bytes-should-tokens-use">
<h3>凭据应当使用多少个字节？<a class="headerlink" href="#how-many-bytes-should-tokens-use" title="永久链接至标题">¶</a></h3>
<p>为了在面对 <a class="reference external" href="https://en.wikipedia.org/wiki/Brute-force_attack">暴力攻击</a> 时保证安全，凭据必须具有足够的随机性。 不幸的是，对随机性是否足够的标准会随着计算机越来越强大并能够在更短时间内进行更多猜测而不断提高。 在 2015 年时，人们认为 32 字节（256 位）的随机性对于 <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code></a> 模块所适合的典型用例来说是足够的。</p>
<p>作为想要自行管理凭据长度的用户，你可以通过为各种 <code class="docutils literal notranslate"><span class="pre">token_*</span></code> 函数指定一个 <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> 参数来显式地指定凭据要使用多大的随机性。 该参数以字节数来表示要使用的随机性大小。</p>
<p>在其他情况下，如果未提供参数，或者如果参数为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则 <code class="docutils literal notranslate"><span class="pre">token_*</span></code> 函数将改用一个合理的默认值。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>该默认值可能在任何时候被改变，包括在维护版本更新的时候。</p>
</div>
</div>
</div>
<div class="section" id="other-functions">
<h2>其他功能<a class="headerlink" href="#other-functions" title="永久链接至标题">¶</a></h2>
<dl class="function">
<dt id="secrets.compare_digest">
<code class="sig-prename descclassname">secrets.</code><code class="sig-name descname">compare_digest</code><span class="sig-paren">(</span><em class="sig-param">a</em>, <em class="sig-param">b</em><span class="sig-paren">)</span><a class="headerlink" href="#secrets.compare_digest" title="永久链接至目标">¶</a></dt>
<dd><p>如果字符串 <em>a</em> 与 <em>b</em> 相等则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>，该处理方式可降低 <a class="reference external" href="https://codahale.com/a-lesson-in-timing-attacks/">定时攻击</a> 的风险。 请参阅 <a class="reference internal" href="hmac.html#hmac.compare_digest" title="hmac.compare_digest"><code class="xref py py-func docutils literal notranslate"><span class="pre">hmac.compare_digest()</span></code></a> 了解更多细节。</p>
</dd></dl>

</div>
<div class="section" id="recipes-and-best-practices">
<h2>应用技巧与最佳实践<a class="headerlink" href="#recipes-and-best-practices" title="永久链接至标题">¶</a></h2>
<p>本节展示了一些使用 <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code></a> 来管理基本安全级别的应用技巧和最佳实践。</p>
<p>生成长度为八个字符的字母数字密码:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">string</span>
<span class="n">alphabet</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">ascii_letters</span> <span class="o">+</span> <span class="n">string</span><span class="o">.</span><span class="n">digits</span>
<span class="n">password</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">choice</span><span class="p">(</span><span class="n">alphabet</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">))</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>应用程序不能 <a class="reference external" href="http://cwe.mitre.org/data/definitions/257.html">以可恢复的格式存储密码</a>，无论是用纯文本还是加密。 它们应当使用高加密强度的单向（不可恢复）哈希函数来加盐并生成哈希值。</p>
</div>
<p>生成长度为十个字符的字母数字密码，其中包含至少一个小写字母，至少一个大写字母以及至少三个数字:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">string</span>
<span class="n">alphabet</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">ascii_letters</span> <span class="o">+</span> <span class="n">string</span><span class="o">.</span><span class="n">digits</span>
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
    <span class="n">password</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">choice</span><span class="p">(</span><span class="n">alphabet</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
    <span class="k">if</span> <span class="p">(</span><span class="nb">any</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">islower</span><span class="p">()</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">password</span><span class="p">)</span>
            <span class="ow">and</span> <span class="nb">any</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">isupper</span><span class="p">()</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">password</span><span class="p">)</span>
            <span class="ow">and</span> <span class="nb">sum</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">isdigit</span><span class="p">()</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">password</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="mi">3</span><span class="p">):</span>
        <span class="k">break</span>
</pre></div>
</div>
<p>生成 <a class="reference external" href="https://xkcd.com/936/">XKCD 风格的密码串</a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># On standard Linux systems, use a convenient dictionary file.</span>
<span class="c1"># Other platforms may need to provide their own word-list.</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/usr/share/dict/words&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">words</span> <span class="o">=</span> <span class="p">[</span><span class="n">word</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">f</span><span class="p">]</span>
    <span class="n">password</span> <span class="o">=</span> <span class="s1">&#39; &#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">choice</span><span class="p">(</span><span class="n">words</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">))</span>
</pre></div>
</div>
<p>生成难以猜测的临时 URL，其中包含适合密码恢复应用的安全凭据:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;https://mydomain.com/reset=&#39;</span> <span class="o">+</span> <span class="n">token_urlsafe</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目录</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code> --- 生成安全随机数字用于管理密码</a><ul>
<li><a class="reference internal" href="#random-numbers">随机数</a></li>
<li><a class="reference internal" href="#generating-tokens">生成凭据</a><ul>
<li><a class="reference internal" href="#how-many-bytes-should-tokens-use">凭据应当使用多少个字节？</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-functions">其他功能</a></li>
<li><a class="reference internal" href="#recipes-and-best-practices">应用技巧与最佳实践</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="hmac.html"
                        title="上一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hmac</span></code> --- 基于密钥的消息验证</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="allos.html"
                        title="下一章">通用操作系统服务</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/secrets.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="allos.html" title="通用操作系统服务"
             >下一页</a> |</li>
        <li class="right" >
          <a href="hmac.html" title="hmac --- 基于密钥的消息验证"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" >加密服务</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>